<template>
	<view class="imgList" style="color: #333;" v-if="show&&(!hide)">
		<view :style="[style]" v-for="(item,index) in list" :key="index" class="pr imgBox center_box"
			:class="{'img_border':!hideBor}">
			<block v-if="type=='video'">
				<view class="w-max h-max center_box" style="background-color: #000e;" @click.stop="play(item)">
					<text style="color: #fff;" :style="{fontSize:size/4+'rpx'}">▶</text>
				</view>
			</block>
			<block v-else>
				<image class="w-max h-max" :src="item.path||item" mode="aspectFill"></image>
			</block>
			<view class="">
				<view @click.stop="del(index)" v-if="!disabled" class="close">×</view>
			</view>
		</view>
		<view :style="[style]" v-if="(!disabled)&&list.length<max*1" class="imgBox center_box "
			:class="{'img_border':!hideBor}" @click="setimg()" style="text-align: center;line-height: 1em;">
			<block v-if="src">
				<image :src="src" class="w-max h-max" mode="scaleToFill"></image>
			</block>
			<block v-else>
				<view :style="{fontSize:size/3+'rpx'}">+</view>
				<view :style="{fontSize:size/7+'rpx'}">{{text||(type=='video'?'上传视频':'上传照片')}}</view>
			</block>
		</view>
	</view>
</template>

<script>
	/**
	 * img-list 探迹图片上传组件
	 * @description 此组件一般用图片上传。
	 * @tutorial 张浩
	 * @property {String} size 图片大小 单位rpx 默认200
	 * @property {String} disabled 隐藏上传按钮
	 * @property {String} max 最大上传图片数量 默认1
	 * @property {String} ids 回显 图片id 
	 * @property {String} paths 回显 图片链接
	 * @property {String} type 上传视频 video 上传图片 img 默认img 
	 * @property {Boolean} show 是否隐藏组件 默认true  
	 * @property {Boolean} hide 是否隐藏组件 默认false  
	 * @property {function} @success 获取ids 
	 * @example <imgList @success="ids=>form.id=ids"></imgList> //最常用 只取 id
	 * @example @click="$refs.img.uplode('getImg')" <imgList ref="img" @getImg="e=>{form.id=e.id,form.path_url=e.path}"></imgList>
	 */
	export default {
		name: "imgList",
		props: {
			size: { //图片大小
				default: '200',
			},
			width: {
				default: ''
			},
			height: {
				default: ''
			},
			src: {
				default: ''
			},
			max: { //上传图片数量
				default: 1
			},
			ids: { //回显id
				default: '',
			},
			paths: { //回显图片
				default: '',
			},
			type: {
				default: 'img', //video  视频
			},
			show: {
				default: true, //是否隐藏组件 默认true  
			},
			hide: {
				default: false, //是否隐藏组件 默认false  
			},
			disabled: {
				default: false, //是否阻止操作 默认false
			},
			hideBor: {
				default: false, //是否隐藏border
			},
			// autoplay: {
			// 	default: false, //是否自动播放
			// },
			text: {
				default: '', //展示文本
			}
		},
		computed: {
			style() {
				return {
					"width": (this.width || this.size) + 'rpx',
					"height": (this.height || this.size) + 'rpx'
				}
			}
		},
		data() {
			return {
				list: [], //内部显示的图片数组 [{id:1,path:'https//img.png'}]
			};
		},
		watch: {
			ids(val1, val2) {
				this.setInit()
			},
			paths(val1, val2) {
				this.setInit()
			},
		},
		created() {
			this.setInit()
		},
		methods: {
			setInit() {
				let paths = this.paths,
					ids = this.ids
				if ((!ids) || (!paths)) return //判断有没有传id
				if (this.list.length) return //判断现在是否有值
				paths = paths.toString().split(',')
				ids = ids.toString() //id先转字符串,再转数组
				if (!ids.length) return //判断是否是空数组
				ids=ids.split(',')
				this.list = ids.map((item, index) => {
					return { //回显到内部
						id: item,
						path: paths[index]
					}
				})
				this.success()
			},
			setimg() {
				this.$off('up')
				this.$on('up', res => {
					let item = {}
					item.id = res.id
					item.path = res.path
					this.list.push(item)
					this.success()
				})
				if (this.type == "video") { //视频
					this.upVideo('up')
				} else { //图片
					let count = this.max - this.list.length
					this.upImg('up', count)
				}
			},
			play(item) {
				uni.navigateTo({
					url: '/pages/public/video?src=' + item.path
				})
			},
			del(index) {
				let that = this
				uni.showModal({
					title: '删除',
					content: "确认删除吗",
					success(res) {
						if (res.confirm) {
							that.list.splice(index, 1)
							that.success()
						}
					}
				})
			},
			success() {
				let ids = this.list.map(item => {
					return item.id
				})
				ids = ids.toString()
				this.$emit('success', ids, this.list)
			},
			upImg(emit = '', count = 1) {
				if (!emit) {
					uni.showToast({
						title: '请使用uni.$on接收',
						icon: "none"
					})
					return
				}
				uni.chooseImage({
					count, //最多可以选择的图片张数，默认9
					success: (e) => {
						e.tempFilePaths.map(item => {
							this.uploadFile(item, emit)
						})
					}
				})
			},
			upVideo(emit) { //上传视频
				if (!emit) {
					uni.showToast({
						title: '请使用uni.$on接收',
						icon: "none"
					})
					return
				}
				uni.chooseVideo({
					// sourceType: ['camera', 'album'],//album 从相册选视频，camera 使用相机拍摄，默认为：['album', 'camera']
					success: (e) => {
						// console.log(e);
						// console.log(e.tempFiles[0].thumbTempFilePath);
						this.uploadFile(e.tempFilePath, emit)
					}
				})
			},
			uploadFile(filePath, emit = '') {
				let token = uni.getStorageSync('token')
				let downloadTask = uni.uploadFile({
					header: {
						Authorization: token,
						token: token,
					},
					url: this.$baseUrl + '/system/basic/uploadFile', //仅为示例，非真实的接口地址
					filePath,
					fileType: "image",
					name: 'file',
					success: (res) => {
						if (res.statusCode == 200) {//上传成功
							
							res = JSON.parse(res.data)
							if (res.code == 0) {
								uni.showToast({
									icon: "none",
									title: res.info + ''
								})
								return
							}
							uni.showToast({
								// icon: "none",
								title: '上传成功'
							})
							res = {
								id: res.id,
								path: res.path
							}
							this.$emit(emit, res)
							
						} else {
							uni.showToast({
								icon: "none",
								title: res.statusCode + ''
							})
							console.error(res.data)
						}
					},
					fail() {
						console.error('查看下此处配置有无问题');
					},
					complete() {
						uni.hideLoading()
					}
				});
				uni.showLoading({
					title: '开始上传'
				})
				downloadTask.onProgressUpdate((res) => { //监听下载进度
					console.log('上传进度' + res.progress);
					// console.log('已经下载的数据长度' + res.totalBytesWritten);
					// console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
					// 满足测试条件，取消下载任务。
					// num = res.progress
					// tit = `  资源加载中:${num}%`
					// wobj.setTitle(tit);
					uni.showLoading({
						title: '上传进度' + res.progress
					})
					if (res.progress == '100') {
						// uni.showToast({
						// 	// icon: "none",
						// 	title: '上传成功'
						// })
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.imgList {
		box-sizing: border-box;
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		align-items: center;

		margin-right: -10rpx; //////////

		.imgBox {
			margin: 10rpx;

			margin: 0 10rpx 10rpx 0; //////////


			border-radius: 10rpx;
			// overflow: hidden;
			color: #606266;
		}

		.center_box {
			display: flex;
			flex-direction: column;
			justify-content: space-evenly;
			align-items: center;
		}

		.img_border {
			border: #dddddd dashed 2rpx;
		}

		.close {
			position: absolute;
			top: -8rpx;
			right: -8rpx;
			width: 30rpx;
			height: 30rpx;
			border-radius: 100%;
			line-height: 30rpx !important;
			text-align: center;
			color: #fff;
			background: red;
			z-index: 2;

			// .view {
			// 	position: absolute;
			// 	top: 50%;
			// 	left: 50%;
			// 	transform: translate(-50%, -50%);
			// }
		}

		.pa {
			position: absolute;
		}

		.pr {
			position: relative;
		}

		.w-max {
			width: 100%;
		}

		.h-max {
			height: 100%;
		}
	}
</style>
